﻿using System.Collections.Generic;
using Engine;
using Engine.Graphics;
using Game;

namespace Mekiasm
{
    public class AnimateTextureSystem
    {
        public static object SyncObj=new object();
        public static List<Common.AnimateRender> Renders = new List<Common.AnimateRender>();

        public static void Add(Common.AnimateRender animateRender)
        {
            Common.AnimateRender render = Renders.Find(p => p.Point == animateRender.Point && p.id == animateRender.id);
            if (render == null) Renders.Add(animateRender);
            else render.Created = false;
        }
        public static void Remove(Common.AnimateRender animateRender)
        {
            Common.AnimateRender render = Renders.Find(p => p.Point == animateRender.Point);
            if (render != null) Renders.Remove(render);
        }

        public static void Remove(Point3 point)
        {
            List<Common.AnimateRender> render = Renders.FindAll(p => p.Point == point);
            for (int i=0;i<render.Count;i++) {
                Renders.Remove(render[i]);
            }
        }
        public static void Remove(int d)
        {
            Common.AnimateRender render = Renders.Find(p => p.id == d);
            if (render != null) Renders.Remove(render);
        }

        public static void OnChunkDiscarding(TerrainChunk chunk)
        {
            List<Common.AnimateRender> toRemove = new List<Common.AnimateRender>();
            for (int i = 0; i < Renders.Count; i++)
            {
                Common.AnimateRender drawItem = Renders[i];
                if (Terrain.ToChunk(drawItem.Point.X, drawItem.Point.Z) == chunk.Coords)
                {
                    toRemove.Add(drawItem);
                }
            }
            for (int i = 0; i < toRemove.Count; i++)
            {
                Renders.Remove(toRemove[i]);
            }

        }
        public static void Dispose()
        {
            for (int i = 0; i < Renders.Count; i++)
            {
                Renders[i].RenderTarget?.Dispose();
            }
            Renders.Clear();
        }
        public static void Draw()
        {
            for (int i = 0; i < Renders.Count; i++)
            {
                if (Renders[i].Created == false)
                {
                    Renders[i].OnCreate?.Invoke();
                    Renders[i].Created = true;
                }
                Renders[i]?.Draw();
            }
        }
    }
}
